<template>
  <div>
    <el-form label-position="top" ref="form" :model="form" :rules="formRules">
      <el-form-item prop="id">
        <el-input type="hidden" v-model="form.id"></el-input>
      </el-form-item>
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="文章描述" prop="description">
        <!--TODO 增加图片上传/解析-->
        <div id="vditor-description"></div>
      </el-form-item>
      <el-form-item label="文章正文" prop="content">
        <!--TODO 增加图片上传/解析-->
        <div id="vditor-content"></div>
      </el-form-item>


      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="category">
            <el-select v-model="form.categoryId" placeholder="请选择分类" :filterable="true" style="width: 100%;">
              <el-option :label="item.categoryName" :value="item.id" v-for="item in categoryList"
                         :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="tagList">
            <el-select v-model="form.tagIds" placeholder="请选择标签" :allow-create="true" :filterable="true"
                       :multiple="true" style="width: 100%;">
              <el-option :label="item.tagName" :value="item.id" v-for="item in tagList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-switch
            v-model="form.isPublished"
            active-color="#13ce66"
            active-text="公开"
            style="margin-bottom: 20px;display: block">
        </el-switch>
      </el-form-item>

      <el-form-item style="text-align: left">
        <el-switch
            active-color="#13ce66"
            active-text="置顶"
            v-model="form.isTop"
            style="display: block;margin-bottom: 20px">
        </el-switch>
      </el-form-item>

      <el-form-item style="text-align: left">
        <el-switch
            active-color="#13ce66"
            active-text="推荐"
            v-model="form.isRecommend"
            style="display: block;margin-bottom: 20px">
        </el-switch>
      </el-form-item>


      <el-form-item style="text-align: left">
        <el-switch
            active-color="#13ce66"
            active-text="评论"
            v-model="form.isCommentEnabled"
            style="display: block;margin-bottom: 20px">
        </el-switch>
      </el-form-item>

      <el-form-item style="text-align: left">
        <el-switch
            active-color="#13ce66"
            active-text="赞赏"
            v-model="form.isAppreciation"
            style="display: block;margin-bottom: 20px">
        </el-switch>
      </el-form-item>

      <el-form-item style="text-align: right">
        <el-button type="primary" @click="onSubmit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>


<script>
import Vditor from "vditor"
import "vditor/dist/index.css"

export default {
  name: "WriteBlog",

  data() {
    return {
      form: {
        id: null,
        title: '',
        content: '',
        description: '',
        words: 0, //文章总字数
        readTime: 0,
        categoryId: '',
        userId: 0,
        isPublished: true,
        isTop: true,
        isRecommend: true,
        isAppreciation: true,
        isCommentEnabled: true,
        tagIds: [],
        views: 0
      },
      ready: false,//markdown编辑器是否渲染好了
      descriptionWords: 0,
      contentWords: 0,
      categoryList: [],
      tagList: [],
      vditorDescription: null,
      vditorContent: null,
      formRules: {
        title: [{required: true, message: '请输入标题', trigger: 'blur'}],
        category: [{required: true, message: '请选择分类', trigger: 'blur'}],
        tagList: [{required: true, message: '请选择标签', trigger: 'blur'}],
      },
    }
  },
  methods: {
    onSubmit() {
      this.form.id = this.$route.params.id
      this.form.content = this.vditorContent.getValue();
      this.form.description = this.vditorDescription.getValue();
      this.form.words = this.descriptionWords + this.contentWords;
      this.form.readTime = this.form.words / 100;
      this.form.userId = JSON.parse(localStorage.getItem("user")).id
      console.log("userId:" + this.form.userId)
      this.$http({
        url: (this.$route.params.id == null) ? '/blog/save' : '/blog/update',
        method: "post",
        data: this.form
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$router.push('/blog_list')
          this.$message({
            message: (this.form.id == null) ? '新增博客成功' : '更新博客成功',
            type: 'success'
          });
        } else {
          this.$message({
            message: (this.form.id == null) ? '新增博客失败' : '更新博客失败',
            type: 'error'
          });
        }
      })

    },
    //初始化markdown编辑器
    initVditorDescription() {
      const _this = this //保存this对象
      this.vditorDescription = new Vditor("vditor-description",
          {
            height: 360,
            outline: {
              enable: true //显示大纲
            },
            cache: {//不缓存到localStorage
              enable: false,
            },
            resize: {
              enable: true //可调整高度
            },
            counter: {
              enable: true,
              after(count) {
                _this.descriptionWords = count;
              }
            },
            placeholder: "Vditor 是一款浏览器端的 Markdown 编辑器，支持所见即所得（富文本）、即时渲染（类似 Typora）和分屏预览模式",
            tab: "    ",
            //上传图片
            upload: {
              //允许的图片后缀
              accept: 'image/*,.wav,.jpg,.png,.gif,.jpeg,.svg',
              max: 100 * 1024 * 1024,
              multiple: false,
              // 上传图片要用的url
              url: 'http://localhost/admin/upload/images',
              filename(name) {
                return name.replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, '').replace(
                    /[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, '').replace('/\\s/g', '')
              },
              success(editor, msg) {
                let responseData = JSON.parse(msg)
                console.log(responseData)
                let imageUrl = responseData.url;
                let succFileText = "";
                  succFileText += `\n![${imageUrl}](${imageUrl})`;
                //将图片路径写入文本
                document.execCommand("insertHTML", false, succFileText);
              },
              error() {
                alert('失败');
              }

            },
            after() {
              if (!_this.ready) {
                _this.ready = true;
              } else {
                _this.getBlog();
              }
            }
          }
      )
    },
    initVditorContent() {
      const _this = this
      this.vditorContent = new Vditor("vditor-content",
          {
            height: 360,
            outline: {
              enable: true //显示大纲
            },
            cache: {//不缓存到localStorage
              enable: false,
            },
            resize: {
              enable: true //可调整高度
            },
            counter: {
              enable: true,
              after(count) {
                _this.contentWords = count;
              }
            },
            placeholder: "Vditor 是一款浏览器端的 Markdown 编辑器，支持所见即所得（富文本）、即时渲染（类似 Typora）和分屏预览模式",
            tab: "    ",
            //上传图片
            upload: {
              //允许的图片后缀
              accept: 'image/*,.wav,.jpg,.png,.gif,.jpeg,.svg',
              max: 100 * 1024 * 1024,
              multiple: false,
              // 上传图片要用的url
              url: 'http://localhost/admin/upload/images',
              filename(name) {
                return name.replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, '').replace(
                    /[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, '').replace('/\\s/g', '')
              },
              success(editor, msg) {
                let responseData = JSON.parse(msg)
                console.log(responseData)
                let imageUrl = responseData.url;
                let succFileText = "";
                succFileText += `\n![${imageUrl}](${imageUrl})`;
                //将图片路径写入文本
                document.execCommand("insertHTML", false, succFileText);
              },
              error() {
                alert('失败');
              }

            },
            after() {
              if (!_this.ready) {
                _this.ready = true;
              } else {
                _this.getBlog();
              }
            }

          }
      )
    },
    initVditor() {
      this.initVditorDescription();
      this.initVditorContent();
    },
    //点击查看图片
    clickAndSeeImage() {
      const vditorDescription = document.getElementById('vditor-description');
      const vditorContent = document.getElementById("vditor-content");
      vditorDescription.addEventListener("click", (event) => {
        if (event.target.tagName === "IMG") {
          Vditor.previewImage(event.target);
        }
      });
      vditorContent.addEventListener("click", (event) => {
        if (event.target.tagName === "IMG") {
          Vditor.previewImage(event.target);
        }
      });
    },
    //获取所有分类列表
    getCategoryList() {
      this.$http({
        url: '/category/list',
      }).then(({data}) => {
        if (data.code === 0) {
          this.categoryList = data.data;
        }
      })

    },
    //获取所有标签列表
    getTagList() {
      this.$http({
        url: '/tag/list',
      }).then(({data}) => {
        if (data.code === 0) {
          this.tagList = data.data;
        }
      })
    },
    //获取要编辑的博客信息
    getBlog() {
      if (this.$route.params.id) {
        const id = this.$route.params.id;
        this.$http({
          url: `blog/${id}`,
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.form = data.data;
            this.form.categoryId = data.data.category.id
            this.form.tagIds = []
            data.data.tags.forEach(tag => {
              this.form.tagIds.push(tag.id)
            })

            this.vditorDescription.setValue(this.form.description);
            this.vditorContent.setValue(this.form.content);
          }
        })
      } //else {
        // this.form = {}
        // this.vditorDescription.setValue('');
        // this.vditorContent.setValue('');
      //}

    }
  },
  mounted() {
    this.initVditor();
    this.getCategoryList();
    this.getTagList();
    this.clickAndSeeImage();
  },
  watch: {
    //如果路由有变化，会再次执行该方法
    $route: {
      handler: function () {
        this.form = {
          id: null,
          title: '',
          content: '',
          description: '',
          words: 0, //文章总字数
          readTime: 0,
          categoryId: '',
          userId: 0,
          isPublished: true,
          isTop: true,
          isRecommend: true,
          isAppreciation: true,
          isCommentEnabled: true,
          tagIds: [],
          views: 0
        }
        this.ready = true;
        this.descriptionWords = 0
        this.contentWords = 0
        this.vditorDescription.setValue('')
        this.vditorContent.setValue('')
        this.getCategoryList();
        this.getTagList();
      },
      // // 深度观察监听
      // deep: true,
      // immediate: true
    }
  }

}
</script>
